package com.xssq.mvc;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebListener;

import org.apache.commons.lang3.StringUtils;

@WebListener
public class ContainerListener implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		this.registerJspServlet(context);
		this.registerDefaultServlet(context);
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}
	
	/**
	 * 对jsp文件的请求进行映射
	 * 容器默认注册了一个servlet-name叫jsp的servlet来处理所有jsp请求
	 * @see org.apache.jasper.servlet.JspServlet
	 * @param context
	 */
	private void registerJspServlet(ServletContext context) {
		ServletRegistration jspServlet = context.getServletRegistration("jsp");
		jspServlet.addMapping("/index.jsp");
		String jspPath = Config.DEFAULT_JSP_PATH;
		if (StringUtils.isNotEmpty(jspPath)) {
			jspServlet.addMapping(jspPath + "*");
		}
	}
	
	/**
	 * 使用默认的DefaultServlet来处理所有的静态资源请求
	 * 同上，容器默认提供了DefaultServlet
	 * @see org.apache.catalina.servlets.DefaultServlet
	 */
	private void registerDefaultServlet(ServletContext context) {
		ServletRegistration defaultServlet = context.getServletRegistration("default");
		defaultServlet.addMapping("/favicon.ico");
		String staticPath = Config.DEFAULT_STATIC_PATH;
		if (StringUtils.isNotEmpty(staticPath)) {
			defaultServlet.addMapping(staticPath + "*");
		}
	}

}
